package zybRedis

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"strconv"
)

type ZybRedis struct {
	strIp string
	nPort uint32
	dbNum uint32
	conn  redis.Conn
	isInit bool
}

func New(ip string, port uint32, dbnum uint32) * ZybRedis{
	return &ZybRedis{
		strIp: ip,
		nPort: port,
		dbNum: dbnum,
		isInit: false,
	}
}

func (r *ZybRedis) Init() bool {

	var strAddr = r.strIp + ":" + strconv.Itoa(int(r.nPort))
	// connect reids.
	{
		var err error
		r.conn, err = redis.Dial("tcp", strAddr)
		if err != nil {
			fmt.Printf("connect redis fail.addr[%s] err:%s\n", strAddr, err)
			return false
		}
	}

	// select dbnum.
	{
		_, err := r.conn.Do("SELECT", r.dbNum)
		if err != nil {
			fmt.Printf("select dbnum fail. err:%s\n", err)
			return false
		}
	}

	r.isInit = true

	return true
}

func (r *ZybRedis) Destroy() {
	r.conn.Close()
}

func (r *ZybRedis) Conn() redis.Conn {
	return r.conn
}

func (r *ZybRedis)IsInit() bool  {
	return  r.isInit
}